<?php

namespace App\Http\Controllers\Posts;

use App\Models\Comment;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CommentController extends Controller
{
    /** 评论列表 */
    public function index(Request $request)
    {
        $article_id = $request->get('article_id');
        if ($request->isMethod('post')){
            $model = Comment::with(['user','article'])
                ->when(!empty($article_id),function ($query)use($article_id){
                    $query->where('article_id',$article_id);
                })
                ->orderBy('updated_at','asc')
                ->paginate(config('base.limit'));
            return $this->data($model->items(),$model->total());
        }
        return view('posts.comment.index');
    }

    /** 编辑评论 */
    public function edit(Request $request)
    {
        $id = $request->get('id');
        if(empty($id)){
            $model = new  Comment();
        }else{
            $model = Comment::with('article')->where('id',$id)->first();
        }

        if ($request->isMethod('post')){
            $data = $request->all();

            $user_id = empty($data['user_id'])?(User::randId()):$data['user_id'];
            $model->content = $data['content'];
            $model->user_id = $user_id;
            $model->save();

            return $this->success('保存成功!');
        }

        return view('posts.comment.edit',['model'=>$model]);
    }

    /** 删除评论 */
    public function del(Request $request){}
}
